package com.dfiles.view.activity;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import android.app.ActionBar;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.dfiles.Config;
import com.dfiles.R;
import com.dfiles.R.color;
import com.dfiles.bean.DFile;
import com.dfiles.provider.FileIconHelper;
import com.dfiles.provider.FileOrderHelper;
import com.dfiles.provider.FileSortHelper;
import com.dfiles.provider.FileSortHelper.SortMethod;
import com.dfiles.provider.FileTypeHelper;
import com.dfiles.provider.FileTypeHelper.FileTypeAll;
import com.dfiles.provider.Util;
import com.dfiles.utils.DataValidation;
import com.dfiles.utils.FileUtils;
import com.dfiles.utils.SdCardUtil;
import com.dfiles.utils.Task;
import com.dfiles.utils.ThreadWorker;
import com.dfiles.view.DSpinner;
import com.dfiles.view.FileGridItem;
import com.dfiles.view.HListView;
import com.dfiles.view.HListView.OnItemClickListener;

public class ActAllFiles extends BaseActivity implements OnClickListener {
	public static final String TAG = "FileViewFragment";
	private static final int MSG_LOADED_FILE = 100;
	private static final int MSG_LOADED_APP = 110;
	private static final int MSG_LOADED_TYPES = 130;// 获取其它类型
	private Context context;
	private View back;
	private View importView;
	private DSpinner mySpinner;
	private GridView mGridView;
	private ListView mListView;
	private ImageView listType;

	private FileIconHelper iconHelper;
	private FileTypeHelper mFileTypeHelper;
	private FileSortHelper mFileSortHelper;
	private DFilesAdapter mFilesAdapter;
	private Cursor cu = null;
	private FileTypeAll fileType;// 文件类型
	private String rootPath;// 当前的sd卡目录
	private List<DFile> fileList = new ArrayList<DFile>();// 总文件列表
	List<String> listPath = new ArrayList<String>();// sd卡目录
	private DirAdapter dirAdapter = null;
	private HListView listViewH;// 目录
	public static final String TYPEKEY = "typeKey";
	public static final String CATEGORYKEY = "category";
	private int flagViewType;
	private ActionBar bar;
	private View barView;
	private Spinner spinnerDisks;
	private HashMap<String, String> roots = new HashMap<String, String>();
	List<String> cardsPath = new ArrayList<String>();
	private final BroadcastReceiver broadcastRec = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			// SD卡已经成功挂载
			if (action.equals("android.intent.action.MEDIA_MOUNTED")) {
				Toast.makeText(context, "新的设备被挂载", 500).show();
			} else if (action.equals("android.intent.action.MEDIA_REMOVED")// 各种未挂载状态
					|| action.equals("android.intent.action.ACTION_MEDIA_UNMOUNTED") || action.equals("android.intent.action.ACTION_MEDIA_BAD_REMOVAL")) {
			} else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) {// 开始扫描和扫描完成是一对
			} else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {// 扫描完成
				refreshData();
			} else if (action.equals(Intent.ACTION_MEDIA_SHARED)) {// 扩展介质的挂载被解除
																	// (unmount)。因为它已经作为
																	// USB大容量存储被共享
				Toast.makeText(context, " USB 大容量存储被共享...", 500).show();
			} else {
				// Toast.makeText(context, "其他状态...", 0).show();
			}
		}
	};

	// 开始监听
	void watchingExternalStoreage() {
		// 在IntentFilter中选择你要监听的行为
		IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);// sd卡被插入，且已经挂载
		intentFilter.setPriority(1000);// 设置最高优先级
		intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);// sd卡存在但未挂载
		intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);// sd卡被移除
		intentFilter.addAction(Intent.ACTION_MEDIA_SHARED);// sd卡作为USB大容量存储被共享，挂载被解除
		intentFilter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);// sd卡已经从sd卡插槽拔出，但是挂载点还没解除
		intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);// 开始扫描
		intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);// 扫描完成
		intentFilter.addDataScheme("file");
		registerReceiver(broadcastRec, intentFilter);// 注册监听函数
	}

	// 停止监听
	void stopWatchingExternalStorage() {
		unregisterReceiver(broadcastRec);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		/* 在content前添加 */
		// UIHelper.setFullScreen(this);
		context = this;
		Bundle b = getIntent().getExtras();
		if (b == null) {
			fileType = FileTypeAll.FILE_TYPE_FOLDER;
		} else {
			fileType = (FileTypeAll) b.getSerializable("typeKey");
		}
		watchingExternalStoreage();
		setContentView(R.layout.act_all_files);
		initView();
		initListener();
		initData();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		refreshData();
	}

	private void initView() {
		bar = getActionBar();
		bar.setDisplayShowCustomEnabled(true);
		bar.setDisplayShowHomeEnabled(false);
		bar.setDisplayShowTitleEnabled(false);
		bar.setDisplayUseLogoEnabled(false);

		barView = getLayoutInflater().inflate(R.layout.act_all_files_bar, null);
		bar.setCustomView(barView);

		back = barView.findViewById(R.id.rp_explorer_main_p2_back);
		importView = barView.findViewById(R.id.rp_explorer_bar_import);
		mySpinner = (DSpinner) barView.findViewById(R.id.eSpinner);
		listType = (ImageView) barView.findViewById(R.id.rp_explorer_main_p2_list_type);

		mGridView = (GridView) findViewById(R.id.rp_explorer_main_p2_gridview);
		mListView = (ListView) findViewById(R.id.rp_explorer_main_p2_listview);
		listViewH = (HListView) findViewById(R.id.rp_explorer_main_p2_hlist);
		// txtPathView = (TextView)
		// findViewById(R.id.repository_add_right_txt_path);
		listType.setVisibility(View.GONE);
		mGridView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
		mListView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
		spinnerDisks = (Spinner) findViewById(R.id.rp_explorer_main_sp_disks);
		spinnerDisks.setVisibility(fileType == FileTypeAll.FILE_TYPE_FOLDER ? View.VISIBLE : View.GONE);
	}

	/**
	 * 
	 * @Description: 初始化
	 * @return
	 * @return String[]
	 * @throw
	 */
	private String[] initRoots() {
		cardsPath.clear();
		if (SdCardUtil.isSdCardAvailable()) {
			cardsPath.addAll(SdCardUtil.getExtSDCardPaths());
		}
		int cardNum = cardsPath.size();
		String[] rootsStr = new String[cardNum];
		if (cardNum >= 1) {
			rootsStr[0] = "主目录";
			roots.put(cardsPath.get(0), rootsStr[0]);
			if (cardNum == 2) {
				rootsStr[1] = "SD卡";
				roots.put(cardsPath.get(1), rootsStr[1]);
			} else {
				for (int i = 2; i < rootsStr.length; i++) {
					rootsStr[i] = "SD卡" + (i - 1);
					roots.put(cardsPath.get(i), rootsStr[i]);
				}
			}
		}
		return rootsStr;
	}

	private void initData() {
		String rootsStr[] = initRoots();
		int cardNum = rootsStr.length;
		// 建立Adapter并且绑定数据源
		ArrayAdapter<String> _Adapter = new ArrayAdapter<String>(this, R.layout.common_dropdown_item, rootsStr);
		// 绑定 Adapter到控件
		spinnerDisks.setAdapter(_Adapter);
		iconHelper = new FileIconHelper(context);
		flagViewType = Config.FLAG_VIEW_TYPE;
		// 显示类型
		switch (flagViewType) {
		case Config.UI.FLAG_VIEW_DETAIL:
			mGridView.setVisibility(View.GONE);
			mListView.setVisibility(View.VISIBLE);
			break;
		case Config.UI.FLAG_VIEW_GRID:
			mListView.setVisibility(View.GONE);
			mGridView.setVisibility(View.VISIBLE);
			break;
		}
		this.rootPath = Config.SD_CARD_PATH;
		mySpinner.setList(FileOrderHelper.spinnerList, DSpinner.THEME2);
		mFileSortHelper = new FileSortHelper();
		mFileTypeHelper = new FileTypeHelper(context);
		// 路径
		dirAdapter = new DirAdapter(context, listPath);
		mFilesAdapter = new DFilesAdapter(context, fileList);
		// refreshData();
		if (cardNum >= 1) {
			spinnerDisks.setSelection(0, true);
		}
	}

	/**
	 * 
	 * @Description: refresh all data
	 * @param
	 * @return void
	 * @throws
	 */
	private void refreshData() {
		fileList.clear();
		listPath.clear();// 初始化路径
		ThreadWorker.execuse(true, new Task(context) {

			@Override
			public void doInUI(Object obj, Integer what) {
				switch (what) {
				case MSG_LOADED_FILE:
				case MSG_LOADED_APP:
				case MSG_LOADED_TYPES:
					getDisplay().clearChoices();
					mFilesAdapter.notifyDataSetChanged();
					toggleLayout();
					createDirView();
					// 根据名字重新排序
					reOrder(SortMethod.name);
					mySpinner.setSelection(0, true);
				}

			}

			@Override
			public void doInBackground() {
				super.doInBackground();
				switch (fileType) {
				case FILE_TYPE_FOLDER:
					fileList.addAll(loadFilesData(rootPath));
					transfer("files查询完毕", MSG_LOADED_FILE);
					break;
				case FILE_TYPE_APP:
					loadApp();
					transfer("app查询完毕", MSG_LOADED_APP);
					break;
				default:
					cu = mFileTypeHelper.query(fileType, SortMethod.name);
					fileList.addAll(getAllTypeFiles(cu));
					transfer(SortMethod.name + "查询完毕", MSG_LOADED_TYPES);
					break;
				}
			}

		});
	}

	private String getPathFromMap(HashMap<String, String> map, String str) {
		Iterator<String> it = map.keySet().iterator();
		while (it.hasNext()) {
			String keyStr = it.next();
			if (map.get(keyStr).equals(str)) {
				return keyStr;
			}
		}
		return null;
	}

	// 初始化监听器
	private void initListener() {
		back.setOnClickListener(this);
		importView.setOnClickListener(this);
		listType.setOnClickListener(this);
		listViewH.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(ListAdapter adapter, View lastView, View view, int position) {
				// 最后一级目录无需操作
				if (position == listPath.size() - 1) {
					return;
				}
				if (fileType == FileTypeAll.FILE_TYPE_FOLDER) {
					String path = File.separator;
					for (int k = 0; k <= position; k++) {
						if (k == 0) {
							int index = spinnerDisks.getSelectedItemPosition();
							String pathStr = (String) spinnerDisks.getSelectedItem();
							// String pathStr = dirAdapter.getItem(index);
							path = getPathFromMap(roots, pathStr);
						} else {
							path = path + File.separator + listPath.get(k);
						}
					}
					rootPath = path;
					refreshData();
				}
			}
		});
		mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub
				itemClicked(position);
			}
		});
		mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub
				itemClicked(position);
			}
		});
		mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub
				DFile file = mFilesAdapter.getItem(position);
				if (file.isFolder) {
					return true;
				}
				return false;
			}
		});
		mySpinner.setOnItemSelectedListener(new DSpinner.OnItemSelectedListener() {

			@Override
			public void onItemSelected(View view, int position, long id, boolean ascOrDesc) {
				// TODO Auto-generated method stub
				SortMethod sort = null;
				switch (position) {
				case 0:
					sort = SortMethod.name;
					break;
				case 1:
					sort = SortMethod.type;
					break;
				case 2:
					sort = SortMethod.size;
					break;
				case 3:
					sort = SortMethod.date;
					break;
				}
				// 排序
				if (sort != null && mFileSortHelper.getSortMethod() != sort) {
					mFileSortHelper.setSortMethog(sort);
					Collections.sort(fileList, mFileSortHelper.getComparator());
					if (mFilesAdapter != null) {
						getDisplay().clearChoices();
						mFilesAdapter.notifyDataSetChanged();
						createDirView();
					}
					// 隐藏图标
				}
			}
		});
		MMultiChoiceModeListener choiceListener = new MMultiChoiceModeListener();
		mGridView.setMultiChoiceModeListener(choiceListener);
		mListView.setMultiChoiceModeListener(choiceListener);
		spinnerDisks.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub
				rootPath = cardsPath.get(position);
				refreshData();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			}
		});
	}

	private AbsListView getDisplay() {
		return mGridView.isShown() ? mGridView : mListView;
	}

	/**
	 * 
	 * @Description: create the directory array
	 * @param
	 * @return void
	 * @throws
	 */
	private void createDirView() {
		listPath.clear();
		if (fileType == FileTypeAll.FILE_TYPE_FOLDER) {
			splitFilesDir(rootPath);
		} else {
			String typeStr = mFileTypeHelper.getFileTypeString(fileType);
			listPath.add(typeStr);
		}
		listViewH.setAdapter(dirAdapter);
	}

	/**
	 * 
	 * @Description: 重新排序
	 * @param @param sort
	 * @return void
	 * @throws
	 */
	private void reOrder(SortMethod sort) {
		try {
			// 排序
			if (sort != null) {
				mFileSortHelper.setSortMethog(sort);
				Collections.sort(fileList, mFileSortHelper.getComparator());
				if (mFilesAdapter != null) {
					unSelectAll();
				}
				// 隐藏图标
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void toggleLayout() {
		if (flagViewType == Config.UI.FLAG_VIEW_GRID) {
			mListView.setVisibility(View.GONE);
			mGridView.setVisibility(View.VISIBLE);
			mGridView.setAdapter(mFilesAdapter);
		} else if (flagViewType == Config.UI.FLAG_VIEW_DETAIL) {
			mGridView.setVisibility(View.GONE);
			mListView.setVisibility(View.VISIBLE);
			mListView.setAdapter(mFilesAdapter);
		}
	}

	/**
	 * 分离path
	 * 
	 * @param path
	 */

	private void splitFilesDir(String path) {
		if (path == null) {
			return;
		}
		String pathStr = (String) spinnerDisks.getSelectedItem();
		String rootPath = getPathFromMap(roots, pathStr);
		path = path.replaceFirst(rootPath, pathStr);

		String sep = File.separator;
		String[] paths = path.split(sep);
		for (int i = 0; i < paths.length; i++) {
			if (!DataValidation.isEmpty(paths[i])) {
				listPath.add(paths[i]);
			}
		}
	}

	/**
	 * 获取某种类型的文件
	 * 
	 * @return
	 */
	private List<DFile> getAllTypeFiles(Cursor cursor) {
		List<DFile> list = new ArrayList<DFile>();
		try {
			if (cursor.moveToFirst()) {
				do {
					Integer position = Integer.valueOf(cursor.getPosition());
					DFile ef = getFileInfo(cursor);
					list.add(position, ef);
					// checkFile();
				} while (cursor.moveToNext());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cu != null) {
				cu.close();
			}
		}
		return list;
	}

	private DFile getFileInfo(Cursor cursor) {
		// 判断是否已经存在
		return (cursor == null || cursor.getCount() == 0) ? null : Util.getFileInfo(cursor.getString(FileTypeHelper.COLUMN_PATH), context);
	}

	// 初始化grid的中的文件
	private List<DFile> loadFilesData(String parentPath) {
		List<DFile> list = new ArrayList<DFile>();
		this.rootPath = parentPath;
		// 右边列出文件
		File files = new File(rootPath);
		File[] fileArray = files.listFiles();
		String filePath = null;
		if (fileArray != null) {
			for (int j = 0; j < fileArray.length; j++) {
				File fff = fileArray[j];
				if (fff.getName().startsWith(".")) {
					continue;
				}
				DFile ef = new DFile();
				filePath = fff.getAbsolutePath();
				if (fff.isFile()) {
					ef.isFolder = false;
					FileTypeAll type = FileIconHelper.getFileTypeBySuffix(filePath);
					ef.type = type;
				} else {
					ef.isFolder = true;
					ef.type = FileTypeAll.FILE_TYPE_FOLDER;
				}
				long size = fff.length();
				long lastModify = fff.lastModified();
				ef.path = filePath;
				ef.name = fff.getName();
				ef.lastModify = lastModify;
				ef.size = size;
				// 判断是否已经存在
				list.add(ef);
			}
		}
		return list;
	}

	/**
	 * 获取本机应用程序
	 */
	private void loadApp() {
		PackageManager pm = context.getPackageManager();
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);
		List<ResolveInfo> infos = pm.queryIntentActivities(intent, 0);// 查询
		DFile ef = null;
		for (int i = 0; i < infos.size(); i++) {
			ActivityInfo activity = infos.get(i).activityInfo;
			String activityName = activity.name;
			String name = activity.applicationInfo.loadLabel(pm).toString();// apk名字
			String packageName = activity.applicationInfo.packageName;// 包名
			Drawable strIcon = pm.getApplicationIcon(activity.applicationInfo);// app图标
			File f = new File(activity.applicationInfo.publicSourceDir);
			long size = Long.valueOf(f.length());
			long lastModify = f.lastModified();
			ef = new DFile();
			ef.path = (f.getAbsolutePath());
			ef.activityName = (activityName);
			ef.packageName = (packageName);
			ef.name = (name);
			ef.lastModify = (lastModify);
			ef.size = (size);
			ef.type = (FileTypeAll.FILE_TYPE_APP);
			fileList.add(ef);
		}
	}

	private void itemClicked(int position) {
		if (position < 0 || position >= fileList.size()) {
			return;
		}
		DFile v = fileList.get(position);
		if (v == null) {
			return;
		}
		if (v.isFolder) {
			rootPath = v.path;
			refreshData();
		} else {
			DFile file = fileList.get(position);
			FileUtils.previewFile(context, file);
		}
	}

	/**
	 * 
	 * @Title: toggleViewType
	 * @Description: 更改显示类型
	 * @param
	 * @return void
	 * @throws
	 */
	private void toggleViewType() {
		if (flagViewType == Config.UI.FLAG_VIEW_GRID) {
			flagViewType = Config.UI.FLAG_VIEW_DETAIL;
			listType.setImageResource(R.drawable.sel_list_tile_gray);
		} else if (flagViewType == Config.UI.FLAG_VIEW_DETAIL) {
			flagViewType = Config.UI.FLAG_VIEW_GRID;
			listType.setImageResource(R.drawable.sel_list_detail_gray);
		}
		toggleLayout();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.rp_explorer_main_p2_back:
			back();
			break;
		case R.id.rp_explorer_main_p2_list_type:
			toggleViewType();
			break;

		}
	}

	public interface OnViewClickListener {
		void onClicked(int id);
	}

	/**
	 * 
	 * @Title: getFileType
	 * @Description: 获取当前显示的类型
	 * @param @return
	 * @return FileType
	 * @throws
	 */
	public FileTypeAll getFileType() {
		return fileType;
	}

	public String getRootPath() {
		return rootPath;
	}

	/**
	 * 
	 * @Title: setRootPath
	 * @Description: query files data use this input rootpath para
	 * @param @param rootPath
	 * @return void
	 * @throws
	 */
	public void setRootPath(String rootPath) {
		this.rootPath = rootPath;
		refreshData();
	}

	private void back() {
		FileTypeAll type = getFileType();
		if (type == FileTypeAll.FILE_TYPE_FOLDER) {// 文件列表显示上一层目录
			String path = getRootPath();
			if (roots.containsKey(path)) {
				finish();
			} else {
				path = (new File(path)).getParent();
				setRootPath(path);
			}
		} else {
			finish();
		}
	}

	/**
	 * 返回键按下
	 */
	@Override
	public void onBackPressed() {
		back();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		return true;
	}

	public class MMultiChoiceModeListener implements MultiChoiceModeListener {

		@Override
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {
			// TODO Auto-generated method stub
			mActionMode = mode;
			mode.getMenuInflater().inflate(R.menu.act_all_files, menu);
			return true;
		}

		@Override
		public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
			// TODO Auto-generated method stub
			return true;
		}

		@Override
		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
			// TODO Auto-generated method stub
			switch (item.getItemId()) {
			case R.id.menu_act_all_files_ok:
				List<DFile> selected = getSelectedItems();
				Intent intent = new Intent();
				intent.putExtra(Config.FLAG_RESULT_DATA, (Serializable) selected);
				setResult(Activity.RESULT_OK, intent);
				finish();
				break;
			case R.id.menu_act_all_files_select_all:
				selectedAll();
				break;
			case R.id.menu_act_all_files_unselect_all:
				unSelectAll();
				break;
			}
			return true;
		}

		@Override
		public void onDestroyActionMode(ActionMode mode) {

		}

		@Override
		public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
			if (mFilesAdapter.getItem(position).isFolder) {
				getDisplay().clearChoices();
				itemClicked(position);
			} else {
				refreshCheckedViews();
				mFilesAdapter.notifyDataSetChanged();
			}
		}
	}

	private ActionMode mActionMode;

	/**
	 * 
	 * @Description: 全不选
	 * @return void
	 * @throw
	 */
	private void unSelectAll() {
		getDisplay().clearChoices();
		mFilesAdapter.notifyDataSetChanged();
		refreshCheckedViews();
	}

	private void selectedAll() {
		for (int i = 0; i < mFilesAdapter.getCount(); i++) {
			mListView.setItemChecked(i, true);
		}
		refreshCheckedViews();
	}

	/**
	 * 
	 * @Description: 获取选中
	 * @return void
	 * @throw
	 */
	private List<DFile> getSelectedItems() {
		List<DFile> selected = new ArrayList<DFile>();
		SparseBooleanArray sba = getDisplay().getCheckedItemPositions();
		for (int i = 0; i < sba.size(); i++) {
			if (sba.valueAt(i)) {
				selected.add(fileList.get(sba.keyAt(i)));
			}
		}
		return selected;
	}

	/**
	 * 
	 * @Description:选中和非选中引起的view刷新
	 * @return void
	 * @throw
	 */
	private void refreshCheckedViews() {
		if (mActionMode == null) {
			return;
		}
		int selectCount = getDisplay().getCheckedItemCount();
		String subtitle = getResources().getString(R.string.str_choose_count);
		subtitle = String.format(subtitle, selectCount);
		// 使用subtitle不会自动上下居中
		// mActionMode.setSubtitle(subtitle);
		mActionMode.setTitle(subtitle);
	}

	/**
	 * 文件目录adapter
	 * 
	 * @author damon.han
	 * 
	 */
	class DirAdapter extends BaseAdapter {
		class ViewHolder {
			TextView txtView;
			View arrow;
		}

		private List<String> list;

		public DirAdapter(Context context, List<String> list) {
			super();
			this.list = list;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(context).inflate(R.layout.dir_item, parent, false);
				holder.txtView = (TextView) convertView.findViewById(R.id.rp_dir_item_txt);
				holder.arrow = convertView.findViewById(R.id.rp_dir_item_img);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.txtView.setText(list.get(position));

			if (position == list.size() - 1) {
				holder.txtView.setTextColor(context.getResources().getColor(color.black));
				holder.arrow.setVisibility(View.GONE);
			} else {
				holder.txtView.setTextColor(context.getResources().getColor(color.gray));
				holder.arrow.setVisibility(View.VISIBLE);
			}
			return convertView;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public String getItem(int position) {
			// TODO Auto-generated method stub
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

	}

	class DFilesAdapter extends BaseAdapter {
		private Context context;
		private List<DFile> list = new ArrayList<DFile>();

		public DFilesAdapter(Context context, List<DFile> list) {
			this.context = context;
			this.list = list;

		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public DFile getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			FileGridItem itemView = null;
			if (convertView == null) {
				switch (flagViewType) {
				case Config.UI.FLAG_VIEW_GRID:
					itemView = new FileGridItem(context, Config.UI.FLAG_VIEW_GRID, iconHelper);
					break;
				case Config.UI.FLAG_VIEW_DETAIL:
					itemView = new FileGridItem(context, Config.UI.FLAG_VIEW_DETAIL, iconHelper);
					break;
				default:
					break;
				}
				convertView = itemView;
				convertView.setTag(itemView);
			} else {
				itemView = (FileGridItem) convertView.getTag();
			}
			DFile data = list.get(position);
			itemView.setData(data, getDisplay().isItemChecked(position));
			return convertView;
		}

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		stopWatchingExternalStorage();
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
	}
}
